<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { Search, Edit, Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCateStore } from '@/stores/cate.js'
import { useTokenStore } from '@/stores/token.js'
import {
  bookSearchService,
  bookAddService,
  bookDetailService,
  bookUpdateService,
  bookDeleteService
} from '@/api/book.js'

// 类型定义
interface Book {
  id: string
  fcategory: string
  scategory: string
  tcategory: string
  title: string
  author: string
  cover: string
  fId?: number
  sId?: number
  tId?: number
}

interface SearchParams {
  kw: string
  fId: number | string
  sId: number | string
  tId: number | string
}

interface BookForm {
  fId: number | string
  sId: number | string
  tId: number | string
  title: string
  author: string
  cover: string
}

// Store 初始化
const cateStore = useCateStore()
const tokenStore = useTokenStore()

// 状态管理
const loading = ref(false)
const drawerVisible = ref(false)
const formMode = ref<'add' | 'edit'>('add')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref<Book[]>([])

// 分类选择器数据
const cateLevel2 = ref<Array<{ id: number, category: string }>>([])
const cateLevel3 = ref<Array<{ id: number, category: string }>>([])

// 搜索表单
const searchParams = reactive<SearchParams>({
  kw: '',
  fId: '',
  sId: '',
  tId: ''
})

// 图书表单
const bookForm = reactive<BookForm>({
  fId: '',
  sId: '',
  tId: '',
  title: '',
  author: '',
  cover: ''
})

const formRef = ref()

// 表单验证规则
const rules = reactive({
  fId: [{ required: true, message: '请选择一级分类', trigger: 'change' }],
  sId: [{ required: true, message: '请选择二级分类', trigger: 'change' }],
  tId: [{ required: true, message: '请选择三级分类', trigger: 'change' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }]
})

// 一级分类变化处理
const handleFirstLevelChange = (id: number) => {
  const parentCategory = cateStore.cateLevel.find(item => item.id === id)
  cateLevel2.value = parentCategory?.children || []
  searchParams.sId = ''
  bookForm.sId = ''
}

// 二级分类变化处理
const handleSecondLevelChange = (id: number) => {
  const parentCategory = cateLevel2.value.find(item => item.id === id)
  cateLevel3.value = parentCategory?.children || []
  searchParams.tId = ''
  bookForm.tId = ''
}

// 获取图书数据
const fetchBooks = async () => {
  try {
    loading.value = true
    const { data } = await bookSearchService({
      page: currentPage.value,
      size: pageSize.value,
      ...searchParams
    })
    tableData.value = data.records
    total.value = data.total
  } catch (error) {
    ElMessage.error('获取图书数据失败')
  } finally {
    loading.value = false
  }
}

// 页码变化处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchBooks()
}

// 每页条数变化处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchBooks()
}

// 重置搜索表单
const resetSearch = () => {
  searchParams.kw = ''
  searchParams.fId = ''
  searchParams.sId = ''
  searchParams.tId = ''
  cateLevel2.value = []
  cateLevel3.value = []
  fetchBooks()
}

// 打开添加图书表单
const openAddForm = () => {
  formMode.value = 'add'
  drawerVisible.value = true
  nextTick(() => {
    formRef.value?.resetFields()
    bookForm.fId = ''
    bookForm.sId = ''
    bookForm.tId = ''
    bookForm.title = ''
    bookForm.author = ''
    bookForm.cover = ''
  })
}

// 打开编辑图书表单
const openEditForm = async (row: Book) => {
  formMode.value = 'edit'
  drawerVisible.value = true

  try {
    const { data } = await bookDetailService(row.id)
    Object.assign(bookForm, {
      fId: data.fId,
      sId: data.sId,
      tId: data.tId,
      title: data.title,
      author: data.author,
      cover: data.cover
    })

    // 加载关联分类 - 修复部分
    if (data.fId) {
      // 先加载二级分类
      const firstLevel = cateStore.cateLevel.find(item => item.id === data.fId)
      cateLevel2.value = firstLevel?.children || []

      if (data.sId) {
        // 再加载三级分类
        const secondLevel = cateLevel2.value.find(item => item.id === data.sId)
        cateLevel3.value = secondLevel?.children || []
      } else {
        cateLevel3.value = []
      }
    } else {
      cateLevel2.value = []
      cateLevel3.value = []
    }
  } catch (error) {
    ElMessage.error('获取图书详情失败')
    drawerVisible.value = false
  }
}

// 删除图书
const deleteBook = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该图书吗?', '提醒', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await bookDeleteService(id)
    ElMessage.success('删除成功')
    fetchBooks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (formMode.value === 'add') {
      await bookAddService(bookForm)
      ElMessage.success('添加成功')
    } else {
      await bookUpdateService(bookForm)
      ElMessage.success('修改成功')
    }

    drawerVisible.value = false
    fetchBooks()
  } catch (error) {
    if (error !== 'validate') {
      ElMessage.error('操作失败')
    }
  }
}

// 上传封面成功回调
const handleUploadSuccess = (response: any) => {
  bookForm.cover = response.data
}

// 初始化加载数据
fetchBooks()
</script>

<template>
  <el-card class="book-management">
    <template #header>
      <div class="card-header">
        <span class="header-title">图书管理</span>

        <div class="search-container">
          <el-select v-model="searchParams.fId" placeholder="一级分类" clearable @change="handleFirstLevelChange">
            <el-option v-for="item in cateStore.cateLevel" :key="item.id" :label="item.category" :value="item.id" />
          </el-select>

          <el-select v-model="searchParams.sId" placeholder="二级分类" clearable @change="handleSecondLevelChange">
            <el-option v-for="item in cateLevel2" :key="item.id" :label="item.category" :value="item.id" />
          </el-select>

          <el-select v-model="searchParams.tId" placeholder="三级分类" clearable>
            <el-option v-for="item in cateLevel3" :key="item.id" :label="item.category" :value="item.id" />
          </el-select>

          <el-input v-model="searchParams.kw" placeholder="书名/作者/ISBN/出版社" :prefix-icon="Search" clearable />

          <el-button type="primary" @click="fetchBooks">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="openAddForm">添加图书</el-button>
        </div>
      </div>
    </template>

    <!-- 图书表格 -->
    <el-table :data="tableData" border stripe v-loading="loading" style="width: 100%;">
      <el-table-column prop="id" label="ID" width="80" show-overflow-tooltip/>
      <el-table-column prop="fcategory" label="一级分类" min-width="120" />
      <el-table-column prop="scategory" label="二级分类" min-width="120" />
      <el-table-column prop="tcategory" label="三级分类" min-width="120" />
      <el-table-column prop="title" label="标题" min-width="180" show-overflow-tooltip />
      <el-table-column prop="author" label="作者" min-width="120" show-overflow-tooltip />

      <el-table-column label="操作" width="120" align="center">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" circle size="small" @click="openEditForm(row)" />
          <el-button type="danger" :icon="Delete" circle size="small" @click="deleteBook(row.id)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
      :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handlePageChange" class="pagination" />

    <!-- 添加/编辑图书抽屉 -->
    <el-drawer v-model="drawerVisible" :title="formMode === 'add' ? '添加图书' : '编辑图书'" size="40%">
      <el-form ref="formRef" :model="bookForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="一级分类" prop="fId">
          <el-select v-model="bookForm.fId" placeholder="请选择一级分类" @change="handleFirstLevelChange">
            <el-option v-for="item in cateStore.cateLevel" :key="item.id" :label="item.category" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="二级分类" prop="sId">
          <el-select v-model="bookForm.sId" placeholder="请选择二级分类" @change="handleSecondLevelChange">
            <el-option v-for="item in cateLevel2" :key="item.id" :label="item.category" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="三级分类" prop="tId">
          <el-select v-model="bookForm.tId" placeholder="请选择三级分类">
            <el-option v-for="item in cateLevel3" :key="item.id" :label="item.category" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input v-model="bookForm.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-input v-model="bookForm.author" placeholder="请输入作者" />
        </el-form-item>

        <el-form-item label="封面" prop="cover">
          <el-upload class="cover-uploader" :auto-upload="true" :show-file-list="false" action="/api/common/upload"
            name="file" :headers="{ 'token': tokenStore.token }" :on-success="handleUploadSuccess">
            <img v-if="bookForm.cover" :src="bookForm.cover" class="cover-image" />
            <el-icon v-else class="uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-drawer>
  </el-card>
</template>

<style lang="scss" scoped>
.book-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-title {
      font-weight: bold;
      font-size: 16px;
    }

    .search-container {
      display: flex;
      align-items: center;
      gap: 10px;

      .el-select,
      .el-input {
        width: 180px;
      }
    }
  }

  .pagination {
    margin-top: 16px;
    justify-content: flex-end;
  }
}

.cover-uploader {
  :deep() {
    .cover-image {
      width: 150px;
      height: 200px;
      display: block;
      object-fit: cover;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 150px;
      height: 200px;
      text-align: center;
      line-height: 200px;
    }
  }
}
</style>